package cool.taomu.box.netty

import cool.taomu.box.netty.inter.IClientConfigure
import io.netty.bootstrap.Bootstrap
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelInitializer
import io.netty.channel.EventLoopGroup
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import javax.inject.Inject
import javax.inject.Named

class NettyClient {
	@Inject
	@Named("host")
	String host;
	@Inject
	@Named("port")
	int port;

	@Inject
	def void client(IClientConfigure config) {
		val coreNumber = Runtime.getRuntime().availableProcessors;
		var EventLoopGroup group = new NioEventLoopGroup(coreNumber);
		var Bootstrap bootstrap = new Bootstrap().group(group);
		config.bootstrap(bootstrap);
		bootstrap.channel(NioSocketChannel).handler(new ChannelInitializer<SocketChannel>() {
			override protected initChannel(SocketChannel ch) throws Exception {
				config.pipeline(ch.pipeline, ch);
			}
		});
		var ChannelFuture cf = bootstrap.connect(host, port).sync();
		config.channel(cf.channel);
		cf.channel().closeFuture().sync();
		group.shutdownGracefully();
	}
}
